//
//  EditAlarmViewController.m
//  AlarmClock
//
//  Created by Fedor Skrynnikov on 9/27/12.
//  Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//

#import "EditAlarmViewController.h"
#import "Constants.h"
#import "SFADatePicker.h"
#import <QuartzCore/QuartzCore.h>
#import "SQLiteUtil.h"

@interface EditAlarmViewController ()

@end

@implementation EditAlarmViewController

static const int NUMBER_OF_TABLE_SECTIONS = 1;
static const int DATE_PICKER_TAG = 100;
static const int RECURENCE_PICKER_TAG = 101;
static const int DATE_CONFIRM_ACTION_SHEET_TAG = 10;
static const int INSERT_IMAGE_ACTION_SHEET_TAG = 11;
static const int NUMBER_OF_RECURENCE_COMPONENTS= 1;


@synthesize scrollView = _scrollView;
@synthesize cells = _cells;
@synthesize nameTextField = _nameTextField;
@synthesize noteTextField = _noteTextField;
@synthesize addImageButton = _addImageButton;
@synthesize datePickerView = _datePickerView;
@synthesize recurencePicker = _recurencePicker;

@synthesize initData = _initData;


#pragma mark - live cicle methods
- (id) initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        cellIdentifiers = [[NSArray alloc] initWithObjects:NAME_ID, DATE_ID, RECURENCE_ID, NOTE_ID, IMAGE_ID, BUTTONS_ID, nil];
        recurences = [[NSArray alloc] initWithObjects:RECURENCE_DAYLY, RECURENCE_WEEKLY, RECURENCE_MONTHLY, RECURENCE_YEARLY, nil];
    }
    return self;
}

- (void) dealloc{  
    [cellIdentifiers release];
    [recurences release];
    [super dealloc];
}

- (void) popupViewInicialization: (UIView*) view{
    [[view layer] setCornerRadius:16];
    [[view layer] setBorderWidth:3.0];
    [[view layer] setBorderColor: [UIColor whiteColor].CGColor];
    const static CGFloat RED = 10.0/255;
    const static CGFloat GREEN = 25.0/255;
    const static CGFloat BLUE = 68.0/255;
    const static CGFloat ALPHA = 0.9;
    [view setBackgroundColor:[UIColor colorWithRed:RED green:GREEN blue:BLUE alpha:ALPHA]];
    view.center = self.view.center;
}

- (void) viewDidLoad{
    [super viewDidLoad];
    
    /* Date picker popup initialization*/
    [self popupViewInicialization:[self datePickerView]];
    CGRect rect = CGRectMake([self datePickerView].frame.origin.x + 1, 
                              [self datePickerView].frame.origin.y - 30, 
                              [self datePickerView].frame.size.width - 20, 
                              [self datePickerView].frame.size.height - 50);
    SFADatePicker* datePicker = [[SFADatePicker alloc]initWithFrame:rect];
    NSCalendar* calendar = [NSCalendar currentCalendar];
    NSDateComponents* components = [calendar components:(NSHourCalendarUnit|NSMinuteCalendarUnit) fromDate:[NSDate date]];
    NSInteger hourIndex = [components hour] < 12 ? [components hour] - 1 : [components hour] - 12 - 1;
    NSInteger minIndex = [components minute];
    NSInteger ampmIndex = [components hour] < 12 ? 0 : 1;
    [datePicker selectRow:hourIndex inComponent:HOUR_INDEX animated:NO];
    [datePicker selectRow:minIndex inComponent:MINUTE_INDEX animated:NO];
    [datePicker selectRow:ampmIndex inComponent:AMPM_INDEX animated:NO];
    [datePicker setTag:DATE_PICKER_TAG];
    [[self datePickerView] addSubview:datePicker];
    [datePicker release];
    
    /* Recurence picker popup initialization*/
    [self popupViewInicialization:[self recurencePicker]];
    
    /* Cells initialization */
    NSDateFormatter* dateFormater = [[NSDateFormatter alloc]init];
    [dateFormater setDateFormat:DATE_FORMAT];

    UITableViewCell* dateCell = [self.cells objectAtIndex:[cellIdentifiers indexOfObject:DATE_ID]];
    UITableViewCell* recurenceCell = [self.cells objectAtIndex:[cellIdentifiers indexOfObject:RECURENCE_ID]];

    if (self.initData != nil) {
        [self.nameTextField setText:[self.initData objectForKey:NAME_ID]];
        [self.noteTextField setText:[self.initData objectForKey:NOTE_ID]];
        [[dateCell detailTextLabel] setText:[self.initData objectForKey:DATE_ID]];
        [[recurenceCell detailTextLabel] setText:[self.initData objectForKey:RECURENCE_ID]];
    }else {
        [[dateCell detailTextLabel] setText:[dateFormater stringFromDate:[NSDate date]]];
        [[recurenceCell detailTextLabel] setText:[recurences objectAtIndex:DEFAULT_RECURENCE]];
    }
    [dateFormater release];
}

- (void) viewDidUnload{
    [super viewDidUnload];
    
    [_scrollView release];
    _scrollView = nil;
    [_cells release];
    _cells = nil;
    [_initData release];
    _initData = nil;
    [_nameTextField release];
    _nameTextField = nil;
    [_noteTextField release];
    _noteTextField = nil;
    [_addImageButton release];
    _addImageButton = nil;
    [_datePickerView release];
    _datePickerView = nil;
    [_recurencePicker release];
    _recurencePicker = nil;
}

- (BOOL) shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}


#pragma mark - Table view data source

- (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView{
    return NUMBER_OF_TABLE_SECTIONS;
}

- (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return [self.cells count];
}

- (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:[cellIdentifiers objectAtIndex:indexPath.row]];
    
    // Configure the cell...
    if(cell == nil){
        cell = [self.cells objectAtIndex:indexPath.row];
    }

    return cell;
}

-(CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
   return [(UITableViewCell*)[self.cells objectAtIndex:indexPath.row] frame].size.height;
}

- (BOOL) tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath{
    return NO;
}

- (BOOL) tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath{
    return NO;
}

#pragma mark - Table view delegate

- (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableViewCell* cell = [self.cells objectAtIndex:indexPath.row];
    if ([cell.reuseIdentifier isEqualToString:NAME_ID] && ![self.nameTextField isEditing]){
        [self.nameTextField becomeFirstResponder];
        return;
    }
    if ([cell.reuseIdentifier isEqualToString:NOTE_ID] && ![self.noteTextField isEditing]){
        [self.noteTextField becomeFirstResponder];
        return;
    }
    [self.noteTextField resignFirstResponder];
    [self.nameTextField resignFirstResponder];
    
    
    if ([cell.reuseIdentifier isEqualToString:DATE_ID]) {
        [UIView animateWithDuration:0.3 animations:^{
            [[self view] addSubview:[self datePickerView]];
            [((UITableView*)[self view]) setScrollEnabled:NO];
            [self setSubviewsUserInteraction:NO];
            [[self datePickerView] setUserInteractionEnabled:YES];
        }];
    }
    if ([cell.reuseIdentifier isEqualToString:RECURENCE_ID]) {
        [UIView animateWithDuration:0.3 animations:^{
            [[self view] addSubview:[self recurencePicker]];
            [((UITableView*)[self view]) setScrollEnabled:NO];
            [self setSubviewsUserInteraction:NO];
            [[self recurencePicker] setUserInteractionEnabled:YES];
        }];
    }
}

- (void) setSubviewsUserInteraction:(BOOL) value {
    for(UIView* subview in [self.view subviews]){
        [subview setUserInteractionEnabled:value];
    }
}


#pragma mark - main form buttons methods

- (IBAction) doneButtonPressed:(id)sender{
    [sender resignFirstResponder];
}

- (IBAction) saveButtonPressed:(id)sender{
    if (self.nameTextField.text == nil || [[self.nameTextField.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] isEqualToString:@""] ) {
        UIAlertView* alert = [[UIAlertView alloc]initWithTitle:@"Alert" message:@"The name field is empty!" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles: nil];
        [alert show];
        [alert release];
        return;
    }
    
    [self saveAlarm];
    [self.navigationController popViewControllerAnimated:YES];
    
}

- (void) saveAlarm{
    SQLiteUtil* sqlite = [[SQLiteUtil alloc] init];
    NSString* recurence = [[self.cells objectAtIndex:[cellIdentifiers indexOfObject:RECURENCE_ID]] detailTextLabel].text;
    NSString* date = [[self.cells objectAtIndex:[cellIdentifiers indexOfObject:DATE_ID]] detailTextLabel].text;
    [sqlite insertInTable:@"alerts" Name:self.nameTextField.text Note:self.noteTextField.text Recurence:recurence  Date:date];
    [sqlite release];
}


#pragma mark  - datePicker popup buttons methods

- (IBAction) todayButtonPressed:(id)sender{
    SFADatePicker* datePicker = (SFADatePicker*)[self.datePickerView viewWithTag:DATE_PICKER_TAG];
    NSCalendar* calendar = [NSCalendar currentCalendar];
    NSDateComponents* components = [calendar components:(NSDayCalendarUnit|NSHourCalendarUnit|NSMinuteCalendarUnit) fromDate:[NSDate date]];
    NSDateComponents* componentOfDayWidgetCreated =  [calendar components:(NSDayCalendarUnit) fromDate:datePicker.today];
    NSInteger dayIndex = [componentOfDayWidgetCreated day] > [components day] ? [componentOfDayWidgetCreated day] - [components day] : 0;
    NSInteger hourIndex = [components hour] < 12 ? [components hour] - 1 : [components hour] - 12 - 1;
    NSInteger minIndex = [components minute];
    NSInteger ampmIndex = [components hour] < 12 ? 0 : 1;
    [datePicker selectRow:dayIndex inComponent:DATE_INDEX animated:YES];
    [datePicker selectRow:hourIndex inComponent:HOUR_INDEX animated:YES];
    [datePicker selectRow:minIndex inComponent:MINUTE_INDEX animated:YES];
    [datePicker selectRow:ampmIndex inComponent:AMPM_INDEX animated:YES];
}

- (IBAction) selectDateButtonPressed:(id)sender{
    if ([((SFADatePicker*)[[self datePickerView] viewWithTag:DATE_PICKER_TAG]).selectedDate compare:[NSDate date]] == NSOrderedAscending ) {
        UIActionSheet* actionSheet = [[UIActionSheet alloc] initWithTitle:@"Date is in the past. Do you want to select?" delegate:self cancelButtonTitle:@"NO" destructiveButtonTitle:nil otherButtonTitles: @"YES", nil];
        [actionSheet setTag:DATE_CONFIRM_ACTION_SHEET_TAG];
        [actionSheet showInView:self.view];
        [actionSheet release];
    }else{
        [self selectDateFromDatePicker];
    }
}

- (void) selectDateFromDatePicker{
    [((UITableView*)[self view]) setScrollEnabled:YES];
    [self setSubviewsUserInteraction:YES];
    NSDateFormatter* formater = [[NSDateFormatter alloc]init];
    [formater setDateFormat:DATE_FORMAT];
    UITableViewCell* dateCell = [self.cells objectAtIndex:[cellIdentifiers indexOfObject:DATE_ID]];
    [[dateCell detailTextLabel] setText:[formater stringFromDate: ((SFADatePicker*)[[self datePickerView] viewWithTag:DATE_PICKER_TAG]).selectedDate ] ];
    [[self datePickerView] removeFromSuperview]; 
    [formater release];
}

#pragma mark - UIActionSheetDelegate method

- (void) actionSheet:(UIActionSheet *)actionSheet didDismissWithButtonIndex:(NSInteger)buttonIndex{
    switch ([actionSheet tag]) {
        case DATE_CONFIRM_ACTION_SHEET_TAG:{
            static const int YES_BUTTON_INDEX = 0;
            if (buttonIndex == YES_BUTTON_INDEX) {
                [self selectDateFromDatePicker];
            }
            break;
        }
        
        case INSERT_IMAGE_ACTION_SHEET_TAG:{
            static const int TAKE_A_SHOT = 0;
            static const int SELECT_FROM_ALBUM = 1;
            if (buttonIndex == TAKE_A_SHOT) {
                UIImagePickerController* imagePicker = [[UIImagePickerController alloc]init];
                [imagePicker setSourceType:UIImagePickerControllerSourceTypeCamera];
                [imagePicker setDelegate:self];
                [self presentModalViewController:imagePicker animated:YES];
                [imagePicker release];
            }else if(buttonIndex == SELECT_FROM_ALBUM){
                UIImagePickerController* imagePicker = [[UIImagePickerController alloc]init];
                [imagePicker setSourceType:UIImagePickerControllerSourceTypePhotoLibrary];
                [imagePicker setDelegate:self];
                [self presentModalViewController:imagePicker animated:YES];
                [imagePicker release];
            }
            break;
        }
        
        default:
            break;
    }
    
}

#pragma mark - recurence picker popup buttons methods

- (IBAction) selectRecurenceButtonPressed:(id)sender{
    [((UITableView*)[self view]) setScrollEnabled:YES];
    [self setSubviewsUserInteraction:YES];
    UITableViewCell* recurenceCell = [self.cells objectAtIndex:[cellIdentifiers indexOfObject:RECURENCE_ID]];
    UIPickerView* pickerView = (UIPickerView*)[self.recurencePicker viewWithTag:RECURENCE_PICKER_TAG];
    [[recurenceCell detailTextLabel] setText: [recurences objectAtIndex: [pickerView selectedRowInComponent:0]]];
    [[self recurencePicker] removeFromSuperview]; 
}

- (IBAction) customRecurenceButtonPressed:(id)sender{
    
}

#pragma mark - Recurence PickerView DataSource & Delegate

- (NSInteger) numberOfComponentsInPickerView:(UIPickerView *)pickerView{
    return NUMBER_OF_RECURENCE_COMPONENTS;
}

- (NSInteger) pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component{
    return [recurences count];
}

- (NSString *) pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component{
    return [recurences objectAtIndex:row];
}

#pragma mark - Insert Image Button methods

- (IBAction) insertImageButtonePressed:(id)sender{
    UIActionSheet* actionSheet = [[UIActionSheet alloc] initWithTitle:@"" delegate:self cancelButtonTitle:@"Cancel" destructiveButtonTitle:nil otherButtonTitles: @"Take a shot", @"Select from album", nil];
    [actionSheet setTag:INSERT_IMAGE_ACTION_SHEET_TAG];
    [actionSheet showInView:self.view];
    [actionSheet release];
}

- (void) imagePickerControllerDidCancel:(UIImagePickerController *)picker{
    [self dismissModalViewControllerAnimated:YES];
}

- (void) imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
    UIImage* image = [info objectForKey:UIImagePickerControllerOriginalImage];
    [self.addImageButton setImage:image forState:UIControlStateNormal];
    [self dismissModalViewControllerAnimated:YES];
}
@end
